<?php
/**
 * Created by 2019/4/13 0013
 * Effect: TokenValidationMiddleware.php
 * Author: 品花
 * Date: 2019/4/13 0013
 * Time: 上午 10:37
 */

namespace App\Middleware;


use App\Consts\RedisKey;
use App\Model\Authority;
use App\Model\Role;
use App\Utility\Register;
use App\Utility\Response;
use EasySwoole\EasySwoole\Config;
use EasySwoole\RedisPool\Redis;

class AuthMiddleware
{
    protected static $instance;

    public static function getInstance()
    {
        if ( !isset(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }


    /**
     * 获取菜单
     * @param $role_id
     * @return array
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getMenus($role_id){

        if($role_id == 1){
            //超级管理员需要排除不需要的菜单
            $menus = Authority::create()
                ->where('state',1)
                ->where('super_manager_show',1 )
                ->field('id,pid,name,icon,icon_active,route,client_route')
                ->order('order_','DESC')
                ->order('id')
                ->all();

        }else{
            $ids =  Role::create()->where('id',$role_id)->scalar('authority_ids');

            $menus = Authority::create()
                ->where('state',1)
                ->where("id",explode(',',$ids),'in')
                ->where('pid',-1 ,'>')
                ->field('id,pid,name,icon,icon_active,route,client_route')
                ->order('order_','DESC')
                ->order('id')
                ->all();
        }
        if(!$menus){
            return [];
        }
        $array = [];
        foreach ($menus as $item){
            $array[] = $item->toArray();
        }
        $menus =  make_tree($array,'id','pid','child');

        return  $menus;

    }

    /**
     * 获取权限列表
     * @param $role_id
     * @return array
     * @throws \Exception
     */
    public function getAuthority($role_id){


        if($role_id == 1){
            $menus = Authority::create()->all();
        }else{
            $ids = Role::create()->where('id',$role_id)->scalar('authority_ids');
            $ids = explode(',',$ids);
            $ids[] = 22 ;
            $ids[] = 41 ;
            $ids[] = 100 ;
            $ids[] = 109 ;
            $menus = Authority::create()->where("id",$ids,'in')->all();
        }
        if($menus){
            $array = [];
            foreach ($menus as $item){
                $array[] = $item->toArray();
            }
            return   $routes = array_column($array,'route');

        }

        return  [];
    }




    /**
     * 验证后台访问权限
     * @param $request
     * @param $response
     * @return bool
     */
    public function verification($request)
    {
        $uri =  $request->getUri()->getPath();
//        var_dump('menuAuth:'.$uri);
        $module = explode('/',$uri)[1];

        if($module == "admin"){
//            var_dump('verification',Register::getInstance()->get('manager_info')['role_id']);
            $routes = Redis::defer('redis')->get(RedisKey::user_authority_list(Register::getInstance()->get('manager_info')['role_id']));
            if($routes){
                $routes = json_decode($routes,true);
            }else{
                $routes = [];
            }
            $passRoute = Config::getInstance()->getConf('pass_route');
            $routes = array_merge($routes,$passRoute);

            if (!$routes) {
                Response::responseJson(403);
                return false;
            }

            if(!in_array($uri,$routes)){
                Response::responseJson(401);
                return false;
            }
        }


        return true;

    }




}

